<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cSelectEmpList, addEmp, selectEmpById, updateEmpById, delectEmp } from '../../api/emp.js'
import { selectAllDeptInfo } from '../../api/dept.js'


const token = ref('')

// 条件查询用的数据
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})

// 员工数据
const empList = ref([])

// 控制对话框显示
const dialogFormVisible = ref(false)

// 对话框数据
const employee = ref({
  id: '',
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

watch(() => employee.value.exprList, (newVal) => {
  if (employee.value.exprList && employee.value.exprList.length > 0) {
    employee.value.exprList.forEach((expr) => {
      expr.begin = expr.date[0]
      expr.end = expr.date[1]
    })
  }
}, { deep: true })

// 部门数据
const deptInfo = ref([])

// 下拉列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 },
{ name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }])

// 分页条数据、
const currentPage = ref(1)// 页码
const pageSize = ref(10)// 每页展示记录数
const background = ref(true)
const total = ref(0)

//表单校验规则
const rules = ref({
  username: [
    { required: true, message: '用户名是必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2-20 个', trigger: 'blur' },
    { pattern: /^[a-zA-Z]+$/, message: '用户名只能包含字母（大小写均可）', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名是必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2-10 个', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5]+$/,
      message: '姓名只能包含汉字',
      trigger: 'blur'
    }
  ],
  gender: [
    { required: true, message: '性别是必填项', trigger: ['blur', 'change'] },
  ],
  phone: [
    { required: true, message: '用户名是必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2-20 个', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的11位手机号',
      trigger: 'blur'
    }
  ],
})

// 校验值
const empFromRef = ref()


watch(() => searchEmp.value.date, (newval) => {
  if (newval.length == 2) {
    searchEmp.value.begin = newval[0]
    searchEmp.value.end = newval[1]
  } else {
    searchEmp.value.begin = ''
    searchEmp.value.end = ''
  }
})


// 查询员工信息
async function search() {
  const result = await cSelectEmpList(searchEmp.value.name,
    searchEmp.value.gender,
    searchEmp.value.begin,
    searchEmp.value.end,
    currentPage.value,
    pageSize.value)
  if (result.code != 0) {
    empList.value = result.data.rows
    total.value = result.data.total
  }
}

// 查询部门信息
async function searchDept() {
  const result = await selectAllDeptInfo()
  if (result.code != 0) {
    deptInfo.value = result.data
  }
}
// 清空条件查询的数据
function clear() {
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  search()
}

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}

// 获取token
function getToken() {
  let loginUser = JSON.parse(localStorage.getItem('loginUser'))
  if (loginUser && loginUser.token) {
    token.value = loginUser.token
  }
}

// 员工工作信息展示
function addEmpExpr() {
  employee.value.exprList.push({ company: '', job: '', begin: '', end: '', date: [] })
}
function delectEmpExpr(index) {
  employee.value.exprList.splice(index, 1)
}

function clearEmployee() {
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entrydate: '',
    image: '',
    exprList: []
  }

  if (empFromRef.value) {
    empFromRef.value.resetFields()
  }
}

// 添加员工
async function addEmployee() {

  if (!empFromRef.value) return;

  await empFromRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (employee.value.id) {
        //修改
        result = await updateEmpById(employee.value)
      } else {
        //添加
        result = await addEmp(employee.value)
      }


      if (result.code) {
        ElMessage.success('保存成功!')
        dialogFormVisible.value = false
        search()
        clearEmployee()
      } else {
        ElMessage.error('保存失败!')
      }
    } else {
      console.log('表单校验不通过')
    }
  })





}

// 查询员工(ID)
async function searchEmpById(id) {

  const result = await selectEmpById(id)
  if (result.code) {
    employee.value = result.data

    if (employee.value.exprList) {
      employee.value.exprList.forEach((empExpr) => {
        empExpr.date = [empExpr.begin, empExpr.end]
      })
    }
  }

  dialogFormVisible.value = true
}

// 根据id删除员工
// async function delectEmpById(id) {
//   const result = await delectEmp(id)
//   if (result.code != 0) {
//     ElMessage.success('删除成功')
//   }

// }

// 删除消息提示框
const delectEmpById = async (id) => {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '删除员工',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await delectEmp(id)
      if (result.code !== 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        search()
        selectionIds.value = []
      } else {
        ElMessage({
          type: 'error',
          message: result.msg,
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


// 批量删除员工
const delectEmpByIds = async () => {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '删除员工',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectionIds.value == null || selectionIds.value.length == 0) {
        ElMessage.error('请选择你要删除的员工!')
        return;
      }

      const result = await delectEmp(selectionIds.value)
      if (result.code !== 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        search()
        selectionIds.value = []
      } else {
        ElMessage({
          type: 'error',
          message: result.msg,
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

//
const selectionIds = ref([])
function handleSelectionChange(selectionVal) {
  selectionIds.value = selectionVal.map((emp) => emp.id)
}

// 文件上传
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data
}
const beforeAvatarUpload = (file) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
    ElMessage.error('只支持 .jpeg .png 格式')
    return false
  } else if (file.size / 1024 / 1024 > 10) {
    ElMessage.error('只支持上传 10M 大小的图片')
    return false
  }
  return true
}

onMounted(() => {
  search()
  searchDept()
  getToken()
})
</script>



<template>
  <h1>员工管理</h1>

  <!-- 条件查询表单 -->
  <div class="container">
    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">

      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入姓名" clearable />
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="searchEmp.gender" placeholder="请输入性别" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="入职日期">
        <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="到" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-DD-MM" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 按钮 -->
  <div class="container">
    <el-button type="primary" @click="dialogFormVisible = true">新增员工</el-button>
    <el-button type="danger" @click="delectEmpByIds()">批量删除</el-button>
  </div>

  <!-- 表格 -->
  <div class="container">
    <el-table :data="empList" border class="el-table" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="姓名" width="100" prop="name" align="center" />
      <el-table-column label="性别" width="100" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>

      </el-table-column>
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <img :src="scope.row.image" style="width: 50px; height: 50px;">
        </template>
      </el-table-column>
      <el-table-column label="所属部门" width="100" prop="deptName" align="center" />
      <el-table-column label="职位" width="100 " align="center">
        <template #default="scope">
          <span v-if="scope.row.job == 1">班主任</span>
          <span v-else-if="scope.row.job == 2">讲师</span>
          <span v-else-if="scope.row.job == 3">学工主管</span>
          <span v-else-if="scope.row.job == 4">教研主管</span>
          <span v-else-if="scope.row.job == 5">学工部</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="入职日期" width="200" prop="entryDate" align="center" />
      <el-table-column label="最后操作时间" width="300" prop="updateTime" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="searchEmpById(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="small" @click="delectEmpById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
    :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />

  <!-- 新增员工、批量删除 对话框 -->
  <el-dialog v-model="dialogFormVisible" title="对话框" width="1000">
    <!-- 表单 -->
    <el-form :model="employee" :rules="rules" ref="empFromRef" label-position="left" label-width="75px">
      <!-- 布局 -->
      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employee.username" placeholder="请输入员工用户名, 2-20个字" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="employee.name" placeholder="请输入员工姓名, 2-10个字" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择" style="width: 100%">
              <el-option v-for="g in genders" :key="g.value" :label="g.name" :value="g.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employee.phone" placeholder="请输入员工手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择" style="width: 100%">
              <el-option v-for="job in jobs" :key="job.value" :label="job.name" :value="job.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="employee.salary" placeholder="请输入员工薪资" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择" style="width: 100%">
              <el-option v-for="dept in deptInfo" :key="dept.id" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="employee.entryDate" type="date" placeholder="请输入员工入职日期" value-format="YYYY-MM-DD"
              style="width: 70%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="50">
        <el-col :span="24">
          <el-form-item label="头像">
            <!-- 头像上传 -->
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{ 'token': token }">
              <img v-if="employee.image" :src="employee.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2">
          <span>工作经历</span>
        </el-col>
        <el-col :span="6">
          <el-button @click="addEmpExpr" type="success">添加工作经历</el-button>
        </el-col>
      </el-row>

      <el-row :gutter="3" v-for="(expr, index) in employee.exprList" :key="index" style="margin: 20px 0px;   ">
        <el-col :span="9">
          <el-form-item label="时间" label-width="45px">
            <el-date-picker v-model="expr.date" type="daterange" unlink-panels range-separator="到"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司" label-width="45px">
            <el-input v-model="expr.company" placeholder="请填写公司" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" label-width="45px">
            <el-input v-model="expr.job" placeholder="请填写职位" />
          </el-form-item>
        </el-col>

        <el-col :span="1">
          <el-button @click="delectEmpExpr(index)" type="danger">删除</el-button>
        </el-col>
      </el-row>


      <!-- 表单项
      <el-form-item label="Promotion name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item> -->

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false; clearEmployee()" type="danger">取消</el-button>
        <el-button type="primary" @click="addEmployee()">保存</el-button>
      </div>
    </template>
  </el-dialog>



</template>

<style scoped>
.container {
  margin: 20px 0px;
}


/* 表格边框加粗 */
:deep(.el-table) {
  border: 1px solid #e4dbdb;
}

/* 加粗表格内部边框 */
:deep(.el-table td),
:deep(.el-table th) {
  border: 1px solid #dde6db;
}

/* :deep(.el-input) {
  border: 1px solid #e2e4db;
} */

.avatar-uploader-icon {
  width: 100px;
  height: 100px;
}

.avatar {
  width: 70px;
  height: 70px;
}

:deep(.el-input) {
  width: 100%;
}

/* :deep(.el-date-picker)
{
  width: 100%;
} */
</style>